/**
 * 验证手机号码是否正确，正确返回true
 * @param phoneNumber
 */
function phoneNumberIsRight(phoneNumber) {
    let reg = /^0?1[1-9][0-9]\d{8}$/;
	return reg.test(phoneNumber);
}
let map,geolocation, mapMarker,clickLng,clickLat,placeSearch,cityArea,areaCode,lastCity;
$(function() {
	I('soPhone').value = sessionStorage.getItem(SCS_USER_PHONE), btnIssue = $('#btnIssueService');
	queryAllServiceType();
	//显示高德地图
    showAMap();
	$('#soAddress').focus(function() {
		lastCity = getLastCity();
		if (lastCity != null && !isNull(lastCity.lng) && !isNull(lastCity.lat)){
			I("tipinput").value = lastCity.address;
			clickLng = lastCity.lng;
			clickLat = lastCity.lat;
			addMapMarker(clickLng, clickLat);
			map.setZoomAndCenter(14, [clickLng, clickLat]);
		}
		$('.mask-layer,#amapLayerCenter').show();
	});
	//关闭遮罩层和地图
	$('.close-mask-layer').click(function() {
		$('.mask-layer,#amapLayerCenter').hide();
	});
	$('#btnSureAddress').click(function() {
		let aMapGeocoder = getGeocoder();
		aMapGeocoder.getLocation(V("tipinput"), function(status, result) {
			if (status === 'complete' && result.geocodes.length) {
				let geoObj = result.geocodes[0];
				clickLat = geoObj.location.lat;
				clickLng = geoObj.location.lng;
				cityArea = geoObj.addressComponent.district;
				areaCode = geoObj.adcode;
			}
			sureServiceAddress();//处理服务地址
		});
	});
	//发布服务
	btnIssue.click(function() {
		issueService();
	});
	$('.close-login').click(function () {
		closeLoginWin(btnIssue);
	});
});

//查询所有服务类型
function queryAllServiceType() {
	let sTypeArray = getDictionaries('1');
	if (isNull(sTypeArray)) {
		return;
	}
	let stOptionArr = [];
	//添加服务类型列表
	for (let j = 0; j < sTypeArray.length; j++) {
		let st = sTypeArray[j];
		stOptionArr.push('<option value="' + st.id + '">' + st.dicName + '</option>');
	}
	$('#serviceType').append(stOptionArr.join(''));
}
//显示遮罩层和地图
function showAMap() {
	//加载地图，调用浏览器定位服务
	map = new AMap.Map('aMapContainer', {
	    resizeEnable: true,
	    zoom:11
	});
	//显示比例尺
	let aMapScale = new AMap.Scale({
	    visible: true
	});
	aMapScale.show();
	map.addControl(aMapScale);
    lastCity = getLastCity();
    //如果没有上次城市信息，则重新定位
    if (lastCity == null){
        map.plugin('AMap.Geolocation', function() {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 20000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 3000,        //定位结果缓存0毫秒，默认：0
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition:'RB'
            });
            map.addControl(geolocation);
            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
            AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        });
    }else {//如果城市信息只有城市名，则将地图定位到上次城市
        currentCityName = lastCity.name;
        currentCityCode = lastCity.code;
		if(isNull(lastCity.lng) || isNull(lastCity.lat)){
			map.setCity(currentCityName);
		}else {
			clickLng = lastCity.lng;
			clickLat = lastCity.lat;
			addMapMarker(clickLng, clickLat);
			map.setZoomAndCenter(14, [clickLng, clickLat]);
			regeocoder();
		}
    }

	//为地图注册click事件获取鼠标点击出的经纬度坐标
	map.on('click', function(e) {
	    clickLng = e.lnglat.getLng();
	    clickLat = e.lnglat.getLat();
	    if (mapMarker != null) {
	    	map.remove(mapMarker);//清除原来的标记
		}
	    //给点击的地方添加标记
	    addMapMarker(clickLng, clickLat);
	    //给点标记添加移动结束时监听事件
	    AMap.event.addListener(mapMarker, 'dragend', mapMarkerDrag);
	    regeocoder();
	});
	//输入提示
	let autoOptions = {input: "tipinput"};
	let auto = new AMap.Autocomplete(autoOptions);
	placeSearch = new AMap.PlaceSearch({map: map});  //构造地点查询类
	AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
}

//解析定位结果
function onComplete(data) {
	clickLng = data.position.getLng();
    clickLat = data.position.getLat();
    addMapMarker(clickLng, clickLat);
    map.setZoomAndCenter(14, [clickLng, clickLat]);
	regeocoder();
}
//如果解析精确定位错误，则根据定位的城市名来定位
function onError(e) {
	showCityInfo();
}
//根据IP定位当前城市
function showCityInfo() {
    //实例化城市查询类
    let citysearch = new AMap.CitySearch();
    //自动获取用户IP，返回当前城市
    citysearch.getLocalCity(function(status, result) {
        if (status != 'complete' || result.info != 'OK') {
            return;
        }
		if (result && result.city && result.bounds) {
			currentCityName = result.city;
			let nameLen = currentCityName.length;
			let delShiName = currentCityName.substr( nameLen- 1,nameLen);
			if (delShiName == '市'){
				delShiName = currentCityName.substr( 0,nameLen - 1);
			}
			last_city_name = localStorage.getItem(LAST_CITY_NAME_KEY);
			if (last_city_name == currentCityName || delShiName == last_city_name) {
				currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
			}
			//地图显示当前城市
			//map.setBounds(result.bounds);
		}
    });
}
//当选中某条记录时会触发
function select(e) {
	let selectAddressObj = e.poi;
	let eAddress = selectAddressObj.district;
	let cityAreaArr = eAddress.split('市');
	let eCity = cityAreaArr[0];
	if (eCity.indexOf('省') > 0){
		eCity = eCity.split('省')[1];
	}
	cityArea = cityAreaArr[1];
	areaCode = selectAddressObj.adcode;
	if (isNull(currentCityName)) {
		currentCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
	}
	if (isNull(currentCityName)) {
		//重新定位城市名
		let citySearch = new AMap.CitySearch();
		//自动获取用户IP，返回当前城市
		citySearch.getLocalCity(function(status, result) {
			if (status === 'complete' && result.info === 'OK' && result && result.city && result.bounds) {
				currentCityName = result.city;
				currentCityCode = getCityIdByName(currentCityName);
			}
		});
	}
	//判断当前浏览器定位的城市跟订单地址是否一致，不一致，则提示是否切换
	if (currentCityName != eCity) {
		if (confirm('您发布的服务的城市是<' + eCity + '>，是否切换到该城市？')) {
			currentCityName = eCity;
			currentCityCode = getCityIdByName(currentCityName);
		}
	}
	let keyStr = selectAddressObj.name;
    placeSearch.setCity(selectAddressObj.adcode);
    placeSearch.search(keyStr);  //关键字查询查询
    clickLng = selectAddressObj.location.lng;
    clickLat = selectAddressObj.location.lat;
	addMapMarker(clickLng, clickLat);
	if (keyStr.indexOf(cityArea) > -1){
		eAddress = eAddress.replace(cityArea,'');
	}
	regeocoder(selectAddressObj.name,eAddress + keyStr);
}
//点标记添加移动结束时监听事件函数
function mapMarkerDrag(e) {
	clickLng = e.lnglat.lng;
    clickLat = e.lnglat.lat;
}
//通过经纬度添加地图标记
function addMapMarker(lng, lat) {
	mapMarker = new AMap.Marker({
   		map: map,
        icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        draggable: true,  //是否可拖动
        position: [lng, lat]
	});
}

/**
 * 获取AMap.Geocoder（地址、经纬度互转）对象
 * @returns {AMap.Geocoder}
 */
function getGeocoder() {
	return new AMap.Geocoder({
		radius: 1000,
		extensions: "all"
	});
}
//逆地理编码,经纬度转地址
function regeocoder(e_poi_name,address) {
	let lnglatXY = [clickLng, clickLat];
	let geocoder = getGeocoder();
    geocoder.getAddress(lnglatXY, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
            geocoderCallBack(result,address);
        }
    });
}

//逆地理编码成功后的回调函数
function geocoderCallBack(data,geocoderAddress) {
	if (isNull(geocoderAddress)){
		geocoderAddress = data.regeocode.formattedAddress;
	}
	let addressObj = data.regeocode.addressComponent; //返回地址描述
    if (isNull(currentCityName)) {
    	currentCityName = addressObj.province;//设置当前默认城市名
	}
    if (isNull(cityArea)) {
    	cityArea = addressObj.district;//设置当前默认区县名
	}
    //区域编码
	areaCode = addressObj.adcode;
    I("tipinput").value = geocoderAddress;
}
//处理服务订单地址
function sureServiceAddress() {
	let mapAddress = V("tipinput");
	if (isNull(clickLat) || isNull(clickLng) || isNull(mapAddress)) {
		alert('获取精确地址失败，请重新输入地址！');
		return;
	}
	let lastCityObj = {
	    'code': currentCityCode,
        'name': currentCityName,
        'lat': clickLat,
        'lng': clickLng,
        'address': mapAddress
    };
	localStorage.setItem(LAST_CITY,JSON.stringify(lastCityObj));
	$('.mask-layer,#amapLayerCenter').hide();
	I('soAddress').value = mapAddress;
}
//发布服务
function issueService() {
	if (!checkServiceForm()) {
		return;
	}
	let userName = sessionStorage.getItem(SCS_USER_NAME);
	if (isNull(userName)) {
		showLoginWindow();
		return;
	}
	if (isNull(cityArea)){
		cityArea = currentCityName + '周边';
	}
    let btnIssue = $('#btnIssueService'), numPrefix = Math.floor(Math.random() * 10) % 2;
	btnIssue.attr({'disabled': true, 'cursor': 'none'});
	btnIssue.text('发布中...');
	$.ajax({
		type: 'post',
		url : '/serviceOrder/saveServiceOrder',
		dataType: 'json',
        async: false,
		timeout: 120000,
		data: {
            'soName': V('soName'),
            'serviceDate': V('soServiceDate'),
            'soServiceType': V('serviceType'),
            'soCityCode': currentCityCode,
            'cityName': currentCityName,
            'cityArea': cityArea,
			'soAreaCode': areaCode,
            'soAddress': V('soAddress'),
            'soPhone': V('soPhone'),
            'soAmount': V('soAmount'),
            'soDesc': V('soDesc'),
            'soBillNumber': numPrefix,
			'soPaymentWay': $('input[name="soPaymentMenthod"]:checked').val(), 'soLng': clickLng,'soLat': clickLat
		},
		success : function (result) {
			if(result.success){
				alert('您的订单发布成功，快去看是谁在抢您的订单吧！');
				$('#serviceOrderForm')[0].reset();
                closeLoginWin(btnIssue);
				return;
			}
			let errorStr = '当前系统繁忙，请稍候再试',ef = result.errorFlag;
			if (ef == '2') {
				errorStr = '[' + V('soServiceDate') + ']不是正确的日期格式';
			}else if (ef == '3') {
                errorStr = '未获取到城市编码';
            } else if (ef == '4') {
                errorStr = '未获取服务标题或联系电话';
            }
			setErrorMsg(errorStr);
			closeLoginWin(btnIssue);
		},
		error: function () {
			setErrorMsg("下单失败，请稍候再试");
			closeLoginWin(btnIssue);
		}
	});
}
/**
 * 关闭登录窗口
 * @param btnIssue 发布服务按钮
 */
function closeLoginWin(btnIssue) {
	$('.mask-layer,#userLogin,.loading').hide();
	btnIssue.attr({'disabled': false, 'cursor': 'pointer'});
	btnIssue.text('发布服务');
}
function setErrorMsg(errorStr) {
	$('#errorMsg').text(errorStr);
}
/**
 * 检查表单必填项
 */
function checkServiceForm() {
    if (isNull(V('soName'))) {
        setErrorMsg('请输入标题');
        return false;
    }
    if (isNull(V('soServiceDate'))) {
        setErrorMsg('请输入服务时间');
        return false;
    }
    if (isNull(clickLat) || isNull(clickLng) || isNull(V("tipinput"))) {
		setErrorMsg('获取精确地址失败，请重新输入地址！');
		return false;
	}
	if (isNull(V('soAddress'))) {
		setErrorMsg('请输入服务地址');
		return false;
	}
	if (isNull(V('soPhone')) || !phoneNumberIsRight(V('soPhone'))) {
		setErrorMsg('请输入正确的手机电话');
		return false;
	}
	if (isNull(V('soAmount')) || parseFloat(V('soAmount')) < 0) {
		setErrorMsg('请输入正确的金额，且不能小于0');
		return false;
	}
	setErrorMsg('');
	return true;
}
/**
 * 显示登录窗口
 */
function showLoginWindow() {
	initVerificationCode();
	let width = $(window).width(), height = $(window).height();
	$('#userLogin').css({'top': ((height - 516) / 2 - 70) + 'px', 'left': (width - 500) / 2 + 'px'});
	$('.mask-layer,#userLogin').show();
	drage = false;
	$('#verifyImgDrag').css('left', 0);
	$('#drag').empty().css({'background-color': '#e8e8e8', 'color': ''});
	//注册验证码拖动事件
	$('#drag').drag(null, null, initVerificationCode);
	I('errorPrompt').innerHTML = '';
}
/**
 * 获取上次的城市对象
 */
function getLastCity() {
    let lc = localStorage.getItem(LAST_CITY);
    return isNull(lc) ? '' : JSON.parse(lc);
}